import {
  pageInfo
} from "../../mock/data";
Page({
  data: {
    isVideoLoading: false, // 这个参数未有实际作用？（未删除，自行更改）
    // tab选中
    currentTab: "catalog", // 默认显示课程目录
    // 课程Id（本来字段是kechenid，修改为courseId）
    courseId: "",
    // 课程章节
    catalogItems: [],
    // 课程章节数量
    kechennub: "",
    // 课程学习数量
    xuexinub: "",
    // 课程的副标题
    fubiaoti: "",
    // 当前播放视频标题（若无标题取课程主标题）
    zhubiaoti: "",
    // 当前正在播放视频的编号
    currVideoId: "",
    // 当前正在播放视频的url
    videoSrc: "",
    // 视频播放初始位置
    initialTime: 0,
  },
  // 获取接口数据
  getData(courseId) {
    // mock数据
    const {
      zhutitle,
      futitle,
      gengxinnumber,
      usernumber,
      zhangjie
    } = pageInfo;
    // 若存在播放记录，播放已有视频
    const historyCourse = wx.getStorageSync(`lastVideoProgress${courseId}`) || null;
    let currCourse = {}
    if (historyCourse) {
      currCourse = this.videoLibrary(zhangjie).getCurrentVideo(historyCourse.currVideoId);
    } else {
      // 不存在，直接播放第一条视频
      currCourse = zhangjie?.[0]?.courses?.[0] || {};
    }
    const {
      videoId,
      subTitle,
      videoUrl
    } = currCourse;
    // 打开播放视频所在的目录，展开目录
    const expandCate = this.updateExpandImmutable(zhangjie, videoId);
    this.setData({
      fubiaoti: futitle,
      kechennub: gengxinnumber,
      xuexinub: usernumber,
      catalogItems: expandCate,
      zhubiaoti: subTitle || zhutitle,
      videoSrc: videoUrl,
      currVideoId: videoId,
      initialTime: historyCourse?.currentTime || 0
    });
  },
  // 播放进度变化时触发，event.detail = {currentTime, duration} ；触发频率 250ms 一次
  onVideoTimeUpdate(e) {
    const {
      currentTime,
    } = e.detail;
    this.saveHistory(currentTime)
  },
  saveHistory(currentTime) {
    const {
      courseId,
      currVideoId,
      videoSrc
    } = this.data;
    // 保存当前播放进度到本地存储
    wx.setStorageSync(`lastVideoProgress${courseId}`, {
      courseId,
      videoSrc,
      currVideoId,
      currentTime
    });
  },
  onUnload() {},
  toggleCourses: function (e) {
    const index = e.currentTarget.dataset.index;
    const catalogItems = this.data.catalogItems;
    catalogItems[index].expanded = !catalogItems[index].expanded;
    this.setData({
      catalogItems: catalogItems,
    });
  },
  // 视频加载事件 
  onVideoLoading: function () {
    console.log("正在加载");
    this.setData({
      isVideoLoading: true,
    });
  },
  // 视频开始播放事件
  onVideoPlay: function () {
    console.log("开始播放");
    this.setData({
      isVideoLoading: false,
    });
  },
  // 视频元数据加载完成事件
  onVideoLoadedmetadata: function () {
    console.log("加载完成");
    this.setData({
      isVideoLoading: false,
    });
  },

  onLoad: function (options) {
    // 获取课程Id
    const {
      courseId
    } = options;
    this.setData({
      courseId,
    })
    // 根据课程Id获取课程相关信息
    this.getData(courseId)
  },
  playVideo: function (e) {
    const {
      videoUrl,
      subTitle,
      videoId
    } = e.currentTarget.dataset?.item;
    this.setData({
      videoSrc: videoUrl,
      zhubiaoti: subTitle,
      currVideoId: videoId,
      initialTime: 0
    });
  },
  onError: function (e) {
    console.log(e.detail.errMsg);
  },
  selectTab: function (e) {
    const {
      tab
    } = e.currentTarget.dataset;
    this.setData({
      currentTab: tab,
    });
    // 可以在这里添加代码来更改选中项的样式，不过在WXML中使用hidden属性已经可以实现内容的切换
  },
  videoLibrary(catalogItems = this.data.catalogItems) {
    const videoList = catalogItems.reduce((acc, chapter, chapterIndex) => {
      chapter.courses.forEach((course, courseIndex) => {
        acc.push({
          ...course,
          chapterTitle: chapter.title,
          chapterIndex,
          courseIndex
        });
      });
      return acc;
    }, [])
    // 构建videoId到索引的映射（O(1)查询）
    const videoIdToIndex = new Map(videoList.map((video, index) => [video.videoId, index]));
    //获取下一个视频对象
    function getNextVideo(videoId) {
      if (!videoIdToIndex.has(videoId)) return null; // 处理无效videoId
      const currentIndex = videoIdToIndex.get(videoId);
      const nextIndex = currentIndex + 1;
      return nextIndex < videoList.length ? videoList[nextIndex] : null; // 处理最后一个视频
    }
    // 获取上一个视频对象
    function getPreviousVideo(videoId) {
      if (!videoIdToIndex.has(videoId)) return null; // 处理无效videoId
      const currentIndex = videoIdToIndex.get(videoId);
      const prevIndex = currentIndex - 1;
      return prevIndex >= 0 ? videoList[prevIndex] : null; // 处理第一个视频
    }
    // 获取当前视频信息
    function getCurrentVideo(videoId) {
      if (!videoIdToIndex.has(videoId)) return null;
      const currentIndex = videoIdToIndex.get(videoId);
      return videoList[currentIndex];
    }
    return {
      getNextVideo,
      getPreviousVideo,
      getCurrentVideo
    }
  },
  changeNext() {
    this.nextChange()
  },
  nextChange(msg = '当前已是最后一节') {
    const {
      catalogItems,
      currVideoId
    } = this.data;
    const nextVideo = this.videoLibrary(catalogItems).getNextVideo(currVideoId);
    if (!nextVideo) {
      wx.showToast({
        title: msg,
        icon: 'none'
      })
      return;
    }
    // 章节展开
    const expandCate = this.updateExpandImmutable(catalogItems, nextVideo.videoId);
    this.setData({
      videoSrc: nextVideo.videoUrl,
      currVideoId: nextVideo.videoId,
      zhubiaoti: nextVideo.subTitle,
      initialTime: 0,
      catalogItems: expandCate
    })
  },
  updateExpandImmutable(arr, targetId, key = 'videoId') {
    if (targetId == null) return [...arr]; // 浅拷贝返回
    const idSet = new Set([targetId]);
    // 使用 map 生成新数组
    return arr.map(item => ({
      ...item, // 浅拷贝当前对象
      expanded: item.courses.some(child => idSet.has(child[[key]])) // 计算新的 expand 值
    }));
  },
  onVideoEnd() {
    // 播放结束自动跳转到下一章节
    this.nextChange("已播放完毕")
  }
});